package com.huc.netty.protocol;

import com.huc.netty.handler.RpcServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author huc
 * @version 1.0
 * @note
 * @date 2021/9/16 11:09
 */
@Slf4j
public class NettyServer {
    private String ip; //服务地址
    private int port; //端口

    public NettyServer(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public void start() {
        log.info("===============开启服务端==============");
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new RpcServerInitializer());
        try {
            ChannelFuture future = bootstrap.bind(this.ip, this.port).sync();
            log.info("Server started Success on Port,{}", this.port);
            log.info("服务端{}:{}开启成功", this.ip, this.port);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
